package com.todaynews.home;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.RotateAnimation;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.common.bean.InfoResult;
import com.common.cache.SpCache;
import com.common.logger.Logger;
import com.common.net.ViseHttp;
import com.common.net.callback.ACallback;
import com.common.ui.fragment.BaseFragment;
import com.common.ui.views.brvah.BaseQuickAdapter;
import com.common.ui.views.recycleview.PullLoadMoreRecyclerView;
import com.common.ui.views.statelayout.StateLayout;
import com.google.gson.Gson;
import com.todaynews.R;
import com.todaynews.common.views.TipView;
import com.todaynews.home.adapter.NewsListAdapter;
import com.todaynews.home.adapter.VideoListAdapter;
import com.todaynews.model.NewsData;
import com.todaynews.model.NewsRecord;
import com.todaynews.model.VideoEntity;
import com.todaynews.utils.Constant;
import com.todaynews.model.News;
import com.todaynews.model.NewsResponse;
import com.todaynews.utils.ListUtils;
import com.todaynews.utils.NewsRecordHelper;
import com.todaynews.utils.TransmitConstant;
import com.todaynews.utils.UIUtils;
import com.video.jzvd.Jzvd;
import com.video.jzvd.MyJZVideoPlayerStandard;

import java.util.ArrayList;
import java.util.List;

public class NewsListFragment extends BaseFragment implements View.OnClickListener,
        BaseQuickAdapter.RequestLoadMoreListener{

    private TipView tip_view;
    private StateLayout stateLayout;
    private PullLoadMoreRecyclerView pullLoadMoreRecyclerView;
    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView recyclerView;
    private LinearLayoutManager linearLayoutManager;
    private String channelCode;
    private boolean isVideoList;

    /**
     * 是否是推荐频道
     */
    private boolean isRecommendChannel;
    private List<News> newsList = new ArrayList();
    protected BaseQuickAdapter newsAdapter;

    /**
     * 是否是点击底部标签进行刷新的标识
     */
    private boolean isClickTabRefreshing;
    private RotateAnimation mRotateAnimation;
    private Gson mGson = new Gson();

    //新闻记录
    private NewsRecord mNewsRecord;

    //用于标记是否是首页的底部刷新，如果是加载成功后发送完成的事件
    private boolean isHomeTabRefresh;

    @Override
    public boolean isImmersionBarEnabled() {
        return false;
    }

    @Override
    public int getLayoutResId() {
        return R.layout.fragment_news_list_fragment;
    }

    @Override
    public void bind(View view) {
        super.bind(view);
        tip_view = view.findViewById(R.id.tip_view);
        stateLayout = view.findViewById(R.id.state_layout);
        pullLoadMoreRecyclerView = view.findViewById(R.id.pullLoadMoreRecyclerView);
        swipeRefreshLayout = view.findViewById(R.id.swipeRefreshLayout);
        recyclerView = view.findViewById(R.id.recycler_view);
    }

    @Override
    public void init() {

        channelCode = getArguments().getString(Constant.CHANNEL_CODE);
        isVideoList = getArguments().getBoolean(Constant.IS_VIDEO_LIST, false);
        String[] channelCodes = getActivity().getResources().getStringArray(R.array.channel_code);
        isRecommendChannel = channelCode.equals(channelCodes[0]);//是否是推荐频道

        if (isVideoList) {
            //如果是视频列表
            newsAdapter = new VideoListAdapter(newsList);
        } else {
            //其他新闻列表
            newsAdapter = new NewsListAdapter(channelCode, newsList);
        }

        linearLayoutManager = new LinearLayoutManager(activity);
        pullLoadMoreRecyclerView.init(recyclerView,swipeRefreshLayout);
        pullLoadMoreRecyclerView.setLayoutManager(linearLayoutManager);
        pullLoadMoreRecyclerView.setAdapter(newsAdapter);
        newsAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                News news = newsList.get(position);
                String itemId = news.item_id;
                StringBuffer urlSb = new StringBuffer("http://m.toutiao.com/i");
                urlSb.append(itemId).append("/info/");
                String url = urlSb.toString();//http://m.toutiao.com/i6412427713050575361/info/
                Intent intent = null;
                if (news.has_video) {
                    //视频
                    intent = new Intent(activity, VideoDetailActivity.class);
                    if (Jzvd.CURRENT_JZVD != null) {
                        //传递进度
                        long progress = Jzvd.CURRENT_JZVD.getCurrentPositionWhenPlaying();
                        if (progress != 0) {
                            intent.putExtra(VideoDetailActivity.PROGRESS, progress);
                        }

                        VideoEntity videoDetailInfo = news.video_detail_info;
                        String videoUrl = "";
                        if (videoDetailInfo != null && !TextUtils.isEmpty(videoDetailInfo.parse_video_url)) {
                            videoUrl = videoDetailInfo.parse_video_url;
                        }
                        intent.putExtra(VideoDetailActivity.VIDEO_URL, videoUrl);
                    }
                } else {
                    //非视频新闻
                    if (news.article_type == 1) {
                        //如果article_type为1，则是使用WebViewActivity打开
                        intent = new Intent(activity, WebViewActivity.class);
                        intent.putExtra(WebViewActivity.URL, news.article_url);
                        startActivity(intent);
                        return;
                    }
                    //其他新闻
                    intent = new Intent(activity, NewsDetailActivity.class);
                }
                intent.putExtra(TransmitConstant.CHANNEL_CODE, channelCode);
                intent.putExtra(TransmitConstant.POSITION, position);
                intent.putExtra(TransmitConstant.DETAIL_URL, url);
                intent.putExtra(TransmitConstant.GROUP_ID, news.group_id);
                intent.putExtra(TransmitConstant.ITEM_ID, itemId);
                startActivity(intent);
            }
        });

        newsAdapter.setEnableLoadMore(true);
        newsAdapter.setOnLoadMoreListener(this, recyclerView);

        if (isVideoList) {
            //如果是视频列表，监听滚动
            recyclerView.addOnChildAttachStateChangeListener(new RecyclerView.OnChildAttachStateChangeListener() {
                @Override
                public void onChildViewAttachedToWindow(View view) {

                }
                @Override
                public void onChildViewDetachedFromWindow(View view) {
                    MyJZVideoPlayerStandard jzvd = (MyJZVideoPlayerStandard) view.findViewById(R.id.video_player);
                    if (jzvd != null && jzvd.jzDataSource != null && jzvd.jzDataSource.containsTheUrl(jzvd.jzDataSource.getCurrentUrl())) {
                        Jzvd currentJzvd = Jzvd.CURRENT_JZVD;
                        if (currentJzvd != null && currentJzvd.screen != Jzvd.SCREEN_FULLSCREEN) {
                            Jzvd.releaseAllVideos();
                        }
                    }
                }
            });
        }
    }

    @Override
    public void onClick(View view) {

    }

    @Override
    public void loadData() {
        long lastTime;
        lastTime = SpCache.getInstance().get(channelCode,0);//读取对应频道下最后一次刷新的时间戳
        if (lastTime == 0){
            //如果为空，则是从来没有刷新过，使用当前时间戳
            lastTime = System.currentTimeMillis() / 1000;
        }

        //查找该频道的最后一组记录
        mNewsRecord = NewsRecordHelper.getLastNewsRecord(channelCode);
        if (mNewsRecord == null) {
            //找不到记录，拉取网络数据
            ViseHttp.GET("")
                    .baseUrl("http://is.snssdk.com/api/news/feed/v62/?refer=1&count=20&loc_mode=4&device_id=34960436458&iid=13136511752/")
                    .tag("request")
                    .addParam("category",channelCode)
                    .addParam("min_behot_time",String.valueOf(lastTime))
                    .addParam("last_refresh_sub_entrance_interval",String.valueOf(System.currentTimeMillis()/1000))
                    .request(new ACallback<NewsResponse>() {
                        @Override
                        public void onSuccess(NewsResponse response) {
                            Logger.i("request onSuccess!");
                            if (response != null) {
                                String desc = response.tips.display_info;
                                List<NewsData> data = response.data;
                                List<News> list = new ArrayList<>();
                                if (!ListUtils.isEmpty(data)){
                                    for (NewsData newsData : data) {
                                        News news = new Gson().fromJson(newsData.content, News.class);
                                        list.add(news);
                                    }
                                }
                                //如果是第一次获取数据
                                if (ListUtils.isEmpty(newsList)) {
                                    if (ListUtils.isEmpty(list)) {
                                        //获取不到数据,显示空布局
                                        //stateView.showEmpty();
                                        return;
                                    }
                                    //stateView.showContent();//显示内容
                                }

                                if (ListUtils.isEmpty(list)) {
                                    //已经获取不到新闻了，处理出现获取不到新闻的情况
                                    UIUtils.showToast(UIUtils.getString(R.string.no_news_now));
                                    return;
                                }

                                if (TextUtils.isEmpty(list.get(0).title)) {
                                    //由于汽车、体育等频道第一条属于导航的内容，所以如果第一条没有标题，则移除
                                    list.remove(0);
                                }

                                dealRepeat(list);//处理新闻重复问题

                                newsList.addAll(0, list);
                                newsAdapter.notifyDataSetChanged();
                                tip_view.show(desc);
                                //保存到数据库
                                NewsRecordHelper.save(channelCode, mGson.toJson(list));

                            }
                        }

                        @Override
                        public void onFail(int errCode, String errMsg) {
                            Logger.e("request errorCode:" + errCode + ",errorMsg:" + errMsg);
                        }
                    });
        }else {
            //找到最后一组记录，转换成新闻集合并展示
            List<News> newsList = NewsRecordHelper.convertToNewsList(mNewsRecord.getJson());
            newsList.addAll(newsList);//添加到集合中
            newsAdapter.notifyDataSetChanged();//刷新adapter
            //判断时间是否超过10分钟，如果是则自动刷新
            if (mNewsRecord.getTime() - System.currentTimeMillis() == 10 * 60 * 100) {
            }
        }
    }

    @Override
    public void onLoadMoreRequested() {

    }

    @Override
    protected void onSuccess(int what, InfoResult t) {

    }

    @Override
    protected void onFail(int what, InfoResult t) {

    }

    /**
     * 处理置顶新闻和广告重复
     */
    private void dealRepeat(List<News> newList) {
        if (isRecommendChannel && !ListUtils.isEmpty(newList)) {
            //如果是推荐频道并且数据列表已经有数据,处理置顶新闻或广告重复的问题
            newList.remove(0);//由于第一条新闻是重复的，移除原有的第一条
            //新闻列表通常第4个是广告,除了第一次有广告，再次获取的都移除广告
            if (newList.size() >= 4) {
                News fourthNews = newList.get(3);
                //如果列表第4个和原有列表第4个新闻都是广告，并且id一致，移除
                if (fourthNews.tag.equals(Constant.ARTICLE_GENRE_AD)) {
                    newList.remove(fourthNews);
                }
            }
        }
    }
}
